package com.lee.boot.batch.step;

import com.lee.boot.batch.model.Product;

import org.springframework.batch.core.*;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.stereotype.Component;

/**
 * @author: Lee
 * @Date: 2019/12/25 0025 23:19
 * @Description:
 */
@Component("fileReader")
public class FileReader implements ItemReader<Product>, ItemReadListener , StepExecutionListener {
    @Override
    public Product read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        System.out.println("read");
        return new Product();
    }


    /**
     * Called before {@link ItemReader#read()}
     */
    @Override
    public void beforeRead() {
        System.out.println( "read beforeRead");
    }

    /**
     * Called after {@link ItemReader#read()}.
     * This method is called only for actual items (ie it is not called when the
     * reader returns null).
     *
     * @param item returned from read()
     */
    @Override
    public void afterRead(Object item) {
        System.out.println( "read afterRead");
    }

    /**
     * Called if an error occurs while trying to read.
     *
     * @param ex thrown from {@link }
     */
    @Override
    public void onReadError(Exception ex) {
        System.out.println( "read onReadError");
    }

    /**
     * Initialize the state of the listener with the {@link StepExecution} from
     * the current scope.
     *
     * @param stepExecution instance of {@link StepExecution}.
     */
    @Override
    public void beforeStep(StepExecution stepExecution) {
        System.out.println( "read beforeStep");
    }

    /**
     * Give a listener a chance to modify the exit status from a step. The value
     * returned will be combined with the normal exit status using
     * {@link ExitStatus#and(ExitStatus)}.
     * <p>
     * Called after execution of step's processing logic (both successful or
     * failed). Throwing exception in this method has no effect, it will only be
     * logged.
     *
     * @param stepExecution {@link StepExecution} instance.
     * @return an {@link ExitStatus} to combine with the normal value. Return
     * {@code null} to leave the old value unchanged.
     */
    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        System.out.println( "read afterStep");
        return ExitStatus.COMPLETED;
    }
}
